using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Web;
using Telerik.Web.Mvc.Extensions;
using Telerik.Web.Mvc.Infrastructure;

namespace Telerik.Web.Mvc.UI {
    public class BrowserCollectionBuilder : WebAssetCollectionBuilder {
        private readonly HttpBrowserCapabilities browser;
        private readonly WebAssetCollection assets;
        private readonly IList<string> addedAssets;
        private readonly IList<string> addedGroups;
        private bool browserTest = true;

        public BrowserCollectionBuilder(WebAssetType assetType,
                                        WebAssetCollection assets,
                                        HttpBrowserCapabilities browser)
            : base(assetType, assets) {
            this.browser = browser;
            this.assets = assets;

            addedAssets = new List<string>();
            addedGroups = new List<string>();
        }

        public BrowserCollectionBuilder Test(Func<HttpBrowserCapabilities, bool> browserAction) {
            if(!browserTest)
                return this;

            browserTest = browserAction(browser);

            if(!browserTest)
                Clear();

            return this;
        }

        private void Clear() {
            addedAssets.Each(source => assets.Remove(assets.AssetItems.SingleOrDefault(asset => asset.Source.EndsWith(source, StringComparison.InvariantCultureIgnoreCase))));
            addedGroups.Each(group => assets.Remove(assets.FindGroupByName(group)));
        }

        public new BrowserCollectionBuilder Add(string source) {
            if(browserTest) {
                addedAssets.Add(source);
                base.Add(source);
            }

            return this;
        }

        public new BrowserCollectionBuilder AddGroup(string name, Action<WebAssetGroupBuilder> configureAction) {
            if(browserTest) {
                addedGroups.Add(name);
                base.AddGroup(name, configureAction);
            }

            return this;
        }

        public new BrowserCollectionBuilder AddSharedGroup(string name) {
            if(browserTest) {
                addedGroups.Add(name);
                base.AddSharedGroup(name);
            }

            return this;
        }
    }
}